<?php

namespace App\Repositories;

use OSS\OssClient;
use OSS\Core\OssException;

class OssRepository{


    protected $config = [
        'accessKeyId'          => 'LTAICJODNTYxgY4B',
        'accessKeySecret'      => 'VCo4eILxGiHiRkCdxmPFfPOctjIf5U',
        'endpoint'              => 'oss-cn-beijing.aliyuncs.com',//'image.stjp360.com',
    ];

    protected $bucket = 'imgdir'; //默认bucket

    protected $oss;



    public function __construct()
    {
        $this->oss = new OssClient($this->config['accessKeyId'], $this->config['accessKeySecret'], $this->config['endpoint']);
    }


    /**
     * 创建OSS目录Bucket
     */
    public function createBucket($name)
    {
        try {
            $this->oss->createBucket($name);
            $this->bucket = $name;
        } catch (OssException $e) {
            print $e->getMessage();
        }

    }


    /**
     * @param $content 字符串内容
     * @param $to_file 上传保存文件名
     * @param null $bucket
     * @return array
     */
    public function uploadContentToFile($content, $to_file, $bucket = null)
    {
        try{

            if(is_null($bucket)){
                $bucket = $this->bucket;
            }

            $this->oss->putObject($bucket, $to_file, $content);

        } catch(OssException $e) {

            return ['state' => false, 'msg' => $e->getMessage()];
        }

        return ['state' => true];
    }


    /**
     * @param $from_file 要上传的文件
     * @param $to_file   上传之后的文件名
     * @param null $bucket
     */
    public function uploadFile($from_file, $to_file, $bucket = null)
    {

        try{

            if(is_null($bucket)){
                $bucket = $this->bucket;
            }

            $this->oss->uploadFile($bucket, $to_file, $from_file);

        } catch(OssException $e) {

            return ['state' => false, 'msg' => $e->getMessage()];
        }

        return ['state' => true];
    }




}